package com.candy.candyshortlink.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.candy.candyshortlink.business.entity.ShortLink;
import com.candy.candyshortlink.business.mapper.ShortLinkMapper;
import com.candy.candyshortlink.business.service.IShortLinkService;
import com.gitee.candy.encry.Md5Utils;
import com.gitee.candy.number.ShotChain;
import com.gitee.candy.number.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author suyanlong
 * @since 2023-05-31
 */
@Slf4j
@Service
public class ShortLinkServiceImpl extends ServiceImpl<ShortLinkMapper, ShortLink> implements IShortLinkService {

    @Resource
    SnowflakeIdGenerator snowflakeIdGenerator;

    @Value("${app.domain}")
    String domain; // eg: http://localhost:8080

    @Override
    public ShortLink createShortLink(ShortLink shortLink) {
        // 处理
        this.save(this.createShortChain(shortLink));
        return shortLink;
    }

    @Override
    public List<ShortLink> createShortLinkBatch(List<ShortLink> shortLinkList) {
        shortLinkList.stream().forEach(shortLink -> createShortLink(shortLink));
        this.saveBatch(shortLinkList);
        return shortLinkList;
    }

    @Override
    public ShortLink getByShortUrl(String string) {
        if (string == null) {
            return null;
        }
        synchronized (this) {
            // TODO 获取缓存 返回
            long id = ShotChain.therString(string);
            ShortLink shortLink = getById(id);
            // TODO 存在 存缓存
            return shortLink;
        }
    }

    private ShortLink checkShortLink(ShortLink shortLink) {
        return this.getOne(new QueryWrapper<>(shortLink));
    }

    private ShortLink createShortChain(ShortLink shortLink) {
        shortLink.setSourceUrlMd5(Md5Utils.md5(shortLink.getSourceUrl()));
        /**
         * 1、原链接去重存储 需要校验链接是否存在
         *  优点：节约存储空间
         *  缺点：性能降级，因需要校验是否存在步骤
         * 2、原链接不去重 多次转换生成多个短链接
         *  优点：快
         *  缺点：同一个链接多次转换生成多个短链接，占用空间
         */
        // TODO Url去重校验 布隆过滤器
//        ShortLink checkShort;
//        if ((checkShort = checkShortLink(shortLink)) != null) {
//            return checkShort;
//        }
        shortLink.setId(snowflakeIdGenerator.nextId());
        shortLink.setShortUrl(domain + "/" + ShotChain.toOtherString(shortLink.getId()));
        shortLink.setShortUrlMd5(Md5Utils.md5(shortLink.getShortUrl()));
        shortLink.setCreateTime(LocalDateTime.now());
        shortLink.setUpdateTime(LocalDateTime.now());
        return shortLink;
    }

}
